package org.chs.ts.batch.controller;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.logging.log4j.util.Strings;
import org.chs.ts.base.batch.exec.entity.BatchClearBasicTaskExec;
import org.chs.ts.base.batch.exec.entity.BatchClearBasicTaskStepExec;
import org.chs.ts.base.batch.exec.entity.BatchDailyBasicTaskStepExec;
import org.chs.ts.base.batch.set.entity.BatchDailyBasicTaskPublish;
import org.chs.ts.base.batch.set.entity.BatchDailyBasicTaskStepSet;
import org.chs.ts.base.batch.vo.entity.*;
import org.chs.ts.base.common.util.XssFilterUtils;
import org.chs.ts.base.constant.CommonConstant;
import org.chs.ts.base.vo.Result;
import org.chs.ts.batch.constant.TaskStatusCodeEnum;
import org.chs.ts.batch.exception.TaskExecException;
import org.chs.ts.batch.factory.TaskDailyExecFactory;
import org.chs.ts.batch.factory.TaskExecFactory;
import org.chs.ts.batch.service.IBatchClearBasicTaskExecService;
import org.chs.ts.batch.service.IBatchDailyBasicTaskStepExecService;
import org.chs.ts.batch.thread.BatchThreadPoolProperties;
import org.chs.ts.batch.threadservice.BatchExecService;
import org.chs.ts.batch.util.ConvertToUtil;
import org.chs.ts.batch.util.TaskBuilder;

import org.chs.ts.batch.service.IBatchDailyBasicTaskPublishService;
import org.chs.ts.batch.service.IBatchDailyBasicTaskStepSetService;

import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;
import java.util.Locale;

/**
 * @Compay 盛唐天行
 * @Author: wuwei
 * @Censor By wuwei
 * @Sence 2024/6/13 10:41
 * @Modify 2024/6/13 10:41
 * @Description
 */
@Api(tags = "跑批平台-日间处理控制器")
@RestController
@Slf4j
@RequestMapping("/batchDailyExec")
public class BatchDailyExecController {

    @Resource
    private IBatchClearBasicTaskExecService clearBasicTaskExecService;
    @Resource
    private BatchThreadPoolProperties batchThreadPoolProperties;


    @Resource
    private BatchExecService batchExecService;

    @Resource
    private TaskExecFactory taskExecFactory;

    @Resource
    private TaskBuilder taskBuilder;



    @Resource
    private TaskDailyExecFactory taskDailyExecFactory;
    @Resource
    private IBatchDailyBasicTaskStepSetService dailyBasicTaskStepSetService;

    @Resource
    private IBatchDailyBasicTaskPublishService dailyBasicTaskPublishService;

    @Resource
    private IBatchDailyBasicTaskStepExecService dailyBasicTaskStepExecService;

    @ApiOperation(value = "跑批平台-获取线程池参数", notes = "线程池参数")
    @GetMapping("/getBatcThreadPoolProperties")
    public Result<String> getBatchThreadPoolProperties() {
        String namePrefix = batchThreadPoolProperties.getNamePrefix();
        return Result.ok(namePrefix);
    }

    @ApiOperation(value = "跑批平台-异步执行日间跑批操作", notes = "异步执行日间跑批操作")
    @PostMapping("/process")
    // public BatchExecResp process(@RequestBody BatchExecReq request) {
    public BatchDailyExecResp process(@RequestParam() String taskExecid) {
        BatchDailyExecReq request = new BatchDailyExecReq();
        request.setTaskExecid(XssFilterUtils.filterXss(taskExecid));

        String startTime = ConvertToUtil.getRunningTime();
        BatchDailyExecResp response;
        try {
            // 初始化参数
            request = taskExecFactory.initBatchExecReq(request);
            // 线程池 验证
            taskExecFactory.checkThreadPool();
            //taskExecFactory.checkIsTaskRunningTime(request);
            BatchDailyBasicTaskStepExec taskDailyExec = taskExecFactory.doTaskDailyExec(request.getBatchSysCode(),request.getExecDate(),request.getTaskExecid());
            // 因清算执行时间比较长，页面请求调用清算时，采用异步调用，通过刷新页面获取执行结果
            batchExecService.asyncDoProcess(request, taskDailyExec);
            response = new BatchDailyExecResp(request.getBatchSysCode(), request.getTaskExecid(), "000000",
                    "日间跑批任务调用成功");
        } catch (TaskExecException e) {
            log.error("异步调用日间跑批任务异常：");
            response = new BatchDailyExecResp(request.getBatchSysCode(), request.getTaskExecid(),
                    "999999",
                    e.getMessage());
            return response;
        } catch (Exception e) {
            log.error("异步调用日间跑批任务失败：");
            log.error(e.getMessage(), e);
            response = new BatchDailyExecResp(request.getBatchSysCode(),  request.getTaskExecid(), "999999",
                    "日间跑批任务调用失败" + e.getMessage());
            return response;
        }
        log.info("中间业务批量处理-异步执行日间跑批操作执行耗时:" + ConvertToUtil.getRunningTime(startTime));
        return response;
    }

    /**
     * 针对 当个任务重跑 需要在 跑批任务运行状态停止 。 且 执行线程池中不存在在执行的线程。
     */
    @ApiOperation(value = "跑批平台-异步执行指定跑批操作", notes = "异步执行跑批操作")
    @PostMapping("/processByTaskExecId")
    public BatchExecResp processByTaskExecId(@RequestParam() String taskExecId, @RequestParam() String snatchingMode) {
        BatchExecReq request = new BatchExecReq();
        request.setTaskExecId(XssFilterUtils.filterXss(taskExecId));
        request.setSnatchingMode(XssFilterUtils.filterXss(snatchingMode));
        // todo-wuwei getOne 测试点 如果 getOne 无返回记录 确认 是否 返回null
        BatchClearBasicTaskExec clearBasicTaskExec =
                clearBasicTaskExecService.getOne(new LambdaQueryWrapper<BatchClearBasicTaskExec>().eq(BatchClearBasicTaskExec::getTaskExecid,
                        taskExecId));
        if (clearBasicTaskExec == null) {
            return new BatchExecResp(request.getTaskExecId(), CommonConstant.RTN_CODE_FAILED,
                    "request 请求参数异常！ taskExecId 参数[" + request.getTaskExecId() +
                    "]未获取有效待执行跑批任务清单[BatchClearBasicTaskExec]");
        }
        request.setBatchSysCode(XssFilterUtils.filterXss(clearBasicTaskExec.getBatchSysCode()));
        request.setTaskGroup(XssFilterUtils.filterXss(clearBasicTaskExec.getTaskGroup()));
        request.setExecDate(XssFilterUtils.filterXss(clearBasicTaskExec.getExecDate()));
        String startTime = ConvertToUtil.getRunningTime();
        if (!("redis".equals(request.getSnatchingMode().toLowerCase(Locale.ROOT)) || "database".equals(request.getSnatchingMode().toLowerCase(Locale.ROOT)))) {
            return new BatchExecResp(request.getBatchSysCode(), request.getTaskGroup(), request.getTaskId(), request.getTaskExecId(),
                    CommonConstant.RTN_CODE_FAILED, "request 请求参数异常！ snatchingMode 参数[" + request.getSnatchingMode() + "]不合法！有效参数为redis、database");
        }
        BatchExecResp response;
        try {
            // 初始化参数
            request = taskExecFactory.initBatchExecReq(request);
        } catch (TaskExecException e) {
            // e.printStackTrace();
            log.info(e.getMessage());
            response = new BatchExecResp(request.getBatchSysCode(), request.getTaskGroup(), request.getTaskId(), request.getTaskExecId(),
                    CommonConstant.RTN_CODE_FAILED, "初始化 batchExecReq 对象");
            return response;
        }
        // 先判断 当前 是否 存在 redis 执行分布式锁
        // 如果存在 终止当前请求 反馈错误
        try {
            taskExecFactory.checkIsTaskRunningTime(request);
            // response = new BatchExecResp(request.getTaskGroup(), request.getTaskId(), request.getTaskExecId(), RetCode.FAILED, "当前
            // 存在跑批任务[redis]执行分布式锁！请先关闭跑批任务执行分布式锁！");
            response = new BatchExecResp(request.getBatchSysCode(), request.getTaskGroup(), request.getTaskId(), request.getTaskExecId(),
                    CommonConstant.RTN_CODE_FAILED, "当前 存在跑批任务[redis]执行分布式锁！请先关闭跑批任务执行分布式锁！");
            log.info("当前 存在跑批任务[redis]执行分布式锁！请先关闭跑批任务执行分布式锁！");

            return response;
        } catch (TaskExecException e) {
            log.info("taskExecFactory.checkIsTaskRunningTime 运行异常！" + e.getMessage());
        }
        try {
            // 验证 当前 是否 存在运行中的线程 .
            if (taskExecFactory.getThreadPoolRuningCount() > 0) {
                // 当前存在执行的线程 不允许开启 跑批任务
                throw new TaskExecException("当前跑批线程池存在执行中的任务[" + taskExecFactory.getThreadPoolRuningCount() + "],请稍后再试！",
                        TaskStatusCodeEnum.TASK_ERROR, "");
            }
            BatchClearBasicTaskExec taskExec = taskExecFactory.doTaskExecByTaskExecId(request.getBatchSysCode(), request.getTaskGroup(),
                    request.getExecDate(), request.getTaskExecId(), request.getSnatchingMode());
            List<BatchClearBasicTaskStepExec> taskStepExecList = taskExecFactory.getTaskStepExecListByTaskExec(taskExec);
            // 因清算执行时间比较长，页面请求调用清算时，采用异步调用，通过刷新页面获取执行结果
            batchExecService.asyncDoProcess(request, taskExec, taskStepExecList);
            response = new BatchExecResp(request.getBatchSysCode(), request.getTaskGroup(), request.getTaskId(), request.getTaskExecId(), "000000",
                    "清算任务调用成功");
        } catch (TaskExecException taskExecException) {
            log.error("异步调用清算任务异常：");
            response = new BatchExecResp(request.getBatchSysCode(), request.getTaskGroup(), request.getTaskId(), request.getTaskExecId(), "999999",
                    taskExecException.getMessage());
        } catch (Exception ex) {
            log.error("异步调用清算任务失败：");
            log.error(ex.getMessage(), ex);
            response = new BatchExecResp(request.getBatchSysCode(), request.getTaskGroup(), request.getTaskId(), request.getTaskExecId(), "999999",
                    "清算任务调用失败" + ex.getMessage());
        }
        log.info("中间业务批量处理-异步执行跑批操作执行耗时:" + ConvertToUtil.getRunningTime(startTime));
        return response;
    }

    @ApiOperation(value = "跑批平台-日间跑批抢夺操作", notes = "日间跑批抢夺操作")
    @PostMapping("/getTask")
    public Result<BatchDailyGetTaskResp> getTask(@RequestParam() String batchSysCode, @RequestParam() String execDate, @RequestParam(name = "maxNum"
            , defaultValue = "5", required = false) int maxNum) {
        BatchDailyExecReq request = new BatchDailyExecReq();
        request.setExecDate(XssFilterUtils.filterXss(execDate));
        request.setBatchSysCode(XssFilterUtils.filterXss(batchSysCode));

        String startTime = ConvertToUtil.getRunningTime();
        boolean result = false;
        String errMsg = "";
        BatchDailyGetTaskResp resq;

        try {
            // 验证 execDate 有效性
            taskExecFactory.checkDailyExecDate(request.getExecDate());
            if (!taskExecFactory.checkIsTaskDailyRunningTime(request)) {
                resq = new BatchDailyGetTaskResp();
                resq.setExecDate(request.getExecDate());
                resq.setBatchSysCode(request.getBatchSysCode());
                resq.setRtnCode(CommonConstant.RTN_CODE_FAILED);
                resq.setRtnDesc("request 请求参数异常！batchSysCode or taskDate is null");
                return Result.error("request 请求参数异常！batchSysCode or taskDate is null", resq);

            }
            List<BatchDailyBasicTaskStepExec> taskDailyExec = taskExecFactory.getTaskDailyExec(request.getBatchSysCode(), request.getExecDate(),maxNum);
            if (taskDailyExec.isEmpty()) {
                errMsg = "获取日间跑批抢夺操作失败！";
                String rtnCode = "999999";
                // 增加了 对 当前执行列表判断是否已终止完毕
                if (taskExecFactory.checkTaskDailyExecEnd(request.getBatchSysCode(), request.getExecDate())) {
                    errMsg = "执行日间跑批任务完成！";
                    rtnCode = "111111";
                }
                resq = new BatchDailyGetTaskResp(rtnCode, errMsg);
            } else {
                result = true;
                resq = new BatchDailyGetTaskResp(taskDailyExec, "000000", "执行日间跑批任务调用成功");
            }

        } catch (Exception e) {
            log.error("异步调用日间跑批任务失败：");
            log.error(e.getMessage(), e);
            errMsg = e.getMessage();
            resq = new BatchDailyGetTaskResp("999999", e.getMessage());
            return Result.error(errMsg, resq);
        }
        log.info("跑批平台-跑批抢夺操作执行耗时:" + ConvertToUtil.getRunningTime(startTime));
        if (result) {
            return Result.ok(resq);
        } else {
            return Result.error(errMsg, resq);
        }
    }

    @ApiOperation(value = "跑批平台-初始化跑批任务", notes = "初始化跑批任务")
    @PostMapping("/initTask")
    public Result<String> initTask(@RequestParam() String batchSysCode, @RequestParam() String taskGroup, @RequestParam() String execDate,
                                   @RequestParam() String snatchingMode) {
        BatchExecReq request = new BatchExecReq();
        request.setTaskGroup(XssFilterUtils.filterXss(taskGroup));
        request.setExecDate(XssFilterUtils.filterXss(execDate));
        request.setSnatchingMode(XssFilterUtils.filterXss(snatchingMode));
        request.setBatchSysCode(XssFilterUtils.filterXss(batchSysCode));
        String startTime = ConvertToUtil.getRunningTime();
        boolean result = false;
        String errMsg;
        if (!(StringUtils.hasLength(request.getBatchSysCode()) && StringUtils.hasLength(request.getTaskGroup()) && StringUtils.hasLength(request.getSnatchingMode()) && StringUtils.hasLength(request.getExecDate()))) {
            return Result.error("request 请求参数异常！batchSysCode or taskGroup or snatchingMode or taskDate is null");
        }
        try {
            // 验证 execDate 有效性
            taskExecFactory.checkExecDate(request.getExecDate());
            // 未获取异常 代表 当前执行状态。无法进行重置操作
            taskExecFactory.checkIsTaskRunningTime(request);
            // errMsg = "跑批任务 taskGroup[" + request.getTaskGroup() + "] execDate[" + request.getExecDate() + "] 运行中！无法进行初始化操作！";
        } catch (TaskExecException e) {
            // e.printStackTrace();
            log.info("跑批任务状态确认成功，当前无跑批任务运行！");
        }
        try {
            if (taskExecFactory.initTask(request)) {
                result = true;
                errMsg = "初始化跑批任务成功";
            } else {
                errMsg = "初始化跑批任务失败";

            }
            // errMsg = "初始化跑批任务失败";
        } catch (TaskExecException e) {
            log.error("初始化跑批任务异常：" + e.getMessage());
            errMsg = e.getMessage();
            return Result.error(errMsg);

        } catch (Exception e) {
            log.error("初始化跑批执行异常：" + e.getMessage());
            log.error(e.getMessage(), e);

            errMsg = e.getMessage();
            return Result.error(errMsg);
        }
        log.info("跑批平台-初始化跑批任务执行耗时:" + ConvertToUtil.getRunningTime(startTime));

        if (result) {
            return Result.ok(errMsg);
        } else {
            return Result.error(errMsg);
        }
    }

    @ApiOperation(value = "跑批平台-重置跑批任务", notes = "重置跑批任务将所有已生成任务删除后，重新生成跑批任务清单")
    @PostMapping("/resetTask")
    public Boolean resetTask(@RequestParam() String batchSysCode, @RequestParam() String taskGroup, @RequestParam() String execDate,
                             @RequestParam() String snatchingMode) {
        BatchExecReq request = new BatchExecReq();
        request.setBatchSysCode(XssFilterUtils.filterXss(batchSysCode));
        request.setTaskGroup(XssFilterUtils.filterXss(taskGroup));
        request.setExecDate(XssFilterUtils.filterXss(execDate));
        request.setSnatchingMode(XssFilterUtils.filterXss(snatchingMode));
        String startTime = ConvertToUtil.getRunningTime();

        boolean result = false;
        String errMsg;

        try {
            taskExecFactory.checkIsTaskRunningTime(request);
            errMsg = "跑批平台-重置跑批任务执行存在redis执行全局锁";
            log.error(errMsg);
            log.info("跑批平台-重置跑批任务执行耗时:" + ConvertToUtil.getRunningTime(startTime));
            return false;
        } catch (TaskExecException e) {
            // log.info("taskExecFactory.checkIsTaskRunningTime 运行异常！" + e.getMessage());
        }

        try {
            // errMsg = "重置跑批任务失败";
            // 验证 execDate 有效性
            taskExecFactory.checkExecDate(request.getExecDate());
            // 验证 当前 是否 存在运行中的线程
            if (taskExecFactory.getThreadPoolRuningCount() > 0) {
                // 当前存在执行的线程 不允许开启 跑批任务
                throw new TaskExecException("当前跑批线程池存在执行中的任务[" + taskExecFactory.getThreadPoolRuningCount() + "],请稍后再试！",
                        TaskStatusCodeEnum.TASK_ERROR, "");
            }
            taskExecFactory.forceToStopTaskRunningTime(request);

            if (taskExecFactory.resetTask(request)) {
                result = true;
                errMsg = "重置跑批任务成功";
                log.info(errMsg);
                // return Result.ok("重置跑批任务成功");
            }

            // return Result.error("重置跑批任务失败");

        } catch (TaskExecException e) {
            errMsg = e.getMessage();
            log.info(errMsg);
            return false;

            // return Result.error(e.getMessage());

        } catch (Exception e) {
            log.error("重置跑批任务：");
            log.error(e.getMessage(), e);
            errMsg = e.getMessage();
            log.info(errMsg);
            return result;

            // return Result.error(e.getMessage());
        }

        log.info("跑批平台-重置跑批任务执行耗时:" + ConvertToUtil.getRunningTime(startTime));

        return result;
    }

    @ApiOperation(value = "跑批平台-获取跑批状态", notes = "跑批平台-获取跑批状态")
    @PostMapping("/getTaskRunningStatus")
    public Boolean getTaskRunningStatus(@RequestParam() String batchSysCode, @RequestParam() String taskGroup, @RequestParam() String execDate,
                                        @RequestParam() String snatchingMode) {
        BatchExecReq request = new BatchExecReq();
        request.setBatchSysCode(XssFilterUtils.filterXss(batchSysCode));
        request.setTaskGroup(XssFilterUtils.filterXss(taskGroup));
        request.setExecDate(XssFilterUtils.filterXss(execDate));
        request.setSnatchingMode(XssFilterUtils.filterXss(snatchingMode));

        // String startTime = ConvertToUtil.getRunningTime();
        Boolean result;
        // String msg = "获取跑批状态成功，当前跑批任务";
        try {
            // 验证 execDate 有效性
            taskExecFactory.checkExecDate(request.getExecDate());
            result = taskExecFactory.getTaskRunningStatus(request);
        } catch (TaskExecException e) {
            throw new RuntimeException(e);
        }
        // log.info("中间业务批量处理-获取跑批状态执行耗时:" + ConvertToUtil.getRunningTime(startTime));
        return result;

    }

    /**
     * 获取跑批日间任务请求列表
     *
     * @param taskStepSet {"batchSysCode":"XXXX", "taskPubStatus":"XXX","taskPubId":"XXXX","stepNo":"XXXXX","execCycle":"XXXX","pageNo":"1",
     *                    "pageSize":"20"}
     * @return 分页列表
     */
    @ApiOperation(value = "跑批平台-获取跑批日间任务请求列表", notes = "获取跑批日间任务请求列表")
    @PostMapping("/getDailyTaskPublishList")
    public Result<IPage<BatchDailyBasicTaskPublish>> getDailyTaskPublishList(@RequestBody BatchDailyExecReq taskStepSet) {
        if (Strings.isBlank(taskStepSet.getBatchSysCode()) || Strings.isBlank(taskStepSet.getTaskPubStatus()) || taskStepSet.getPageNo() == null || taskStepSet.getPageSize() == null) {
            return Result.error("请求对象为空不满足查询条件！[batchSysCode]跑批系统代码和[taskPubStatus]跑批日间任务发布状态不能为空！");
        }

        taskStepSet.setBatchSysCode(XssFilterUtils.filterXss(taskStepSet.getBatchSysCode()));
        taskStepSet.setTaskPubStatus(XssFilterUtils.filterXss(taskStepSet.getTaskPubStatus()));
        taskStepSet.setTaskPubId(XssFilterUtils.filterXss(taskStepSet.getTaskPubId()));
        taskStepSet.setStepNo(XssFilterUtils.filterXss(taskStepSet.getStepNo()));
        taskStepSet.setExecCycle(XssFilterUtils.filterXss(taskStepSet.getExecCycle()));

        if (Strings.isNotBlank(taskStepSet.getStepName()) || Strings.isNotBlank(taskStepSet.getExecDate())
                || Strings.isNotBlank(taskStepSet.getExecStartDate()) || Strings.isNotBlank(taskStepSet.getExecEndDate())
                || Strings.isNotBlank(taskStepSet.getExecTime()) || Strings.isNotBlank(taskStepSet.getExecStartTime())
                || Strings.isNotBlank(taskStepSet.getExecEndTime())) {
            log.info("获取跑批日间任务请求列表[getDailyTaskPublishList]请求中包含无效参数！");
        }


        LambdaQueryWrapper<BatchDailyBasicTaskPublish> dailyBasicTaskPublishQuery =
                new LambdaQueryWrapper<BatchDailyBasicTaskPublish>().eq(BatchDailyBasicTaskPublish::getBatchSysCode, taskStepSet.getBatchSysCode())
                        .eq(BatchDailyBasicTaskPublish::getTaskPubStauts, taskStepSet.getTaskPubStatus());

        if (Strings.isNotBlank(taskStepSet.getTaskPubId())) {
            dailyBasicTaskPublishQuery.eq(BatchDailyBasicTaskPublish::getTaskPubId, taskStepSet.getTaskPubId());
        }
        if (Strings.isNotBlank(taskStepSet.getStepNo())) {
            dailyBasicTaskPublishQuery.eq(BatchDailyBasicTaskPublish::getStepNo, taskStepSet.getStepNo());
        }
        if (Strings.isNotBlank(taskStepSet.getStepNo())) {
            dailyBasicTaskPublishQuery.eq(BatchDailyBasicTaskPublish::getStepNo, taskStepSet.getStepNo());
        }
        if (Strings.isNotBlank(taskStepSet.getExecCycle())) {
            dailyBasicTaskPublishQuery.like(BatchDailyBasicTaskPublish::getExecCycle, taskStepSet.getExecCycle());
        }

        Page<BatchDailyBasicTaskPublish> page = new Page<>(taskStepSet.getPageNo(), taskStepSet.getPageSize());

        return Result.ok(dailyBasicTaskPublishService.page(page, dailyBasicTaskPublishQuery));


    }

    /**
     * 获取可发起日间跑批计划模板列表
     *
     * @param taskStepSet {"batchSysCode":"xxx","stepNo":"xxx","stepName":"xxx","pageNo":"1","pageSize":"20"}  <br>
     *                    batchSysCode 、pageNo 、 pageSize 非空限制
     * @return 操作结果
     */
    @ApiOperation(value = "跑批平台-获取可发起日间跑批计划模板列表", notes = "获取可发起日间跑批计划模板列表")
    @PostMapping("/getDailyTaskSetList")
    public Result<IPage<BatchDailyBasicTaskStepSet>> getDailyTaskSetList(@RequestBody BatchDailyExecReq taskStepSet) {
        if (Strings.isBlank(taskStepSet.getBatchSysCode()) || taskStepSet.getPageNo() == null || taskStepSet.getPageSize() == null) {
            return Result.error("请求对象为空不满足查询条件！");
        }

        taskStepSet.setBatchSysCode(XssFilterUtils.filterXss(taskStepSet.getBatchSysCode()));
        taskStepSet.setStepNo(XssFilterUtils.filterXss(taskStepSet.getStepNo()));
        taskStepSet.setStepName(XssFilterUtils.filterXss(taskStepSet.getStepName()));

        LambdaQueryWrapper<BatchDailyBasicTaskStepSet> queryWrapper = new LambdaQueryWrapper<>();
        if (!taskStepSet.getBatchSysCode().isEmpty()) {
            queryWrapper.eq(BatchDailyBasicTaskStepSet::getBatchSysCode, taskStepSet.getBatchSysCode());
        } else {
            return Result.error("跑批系统代码[batchSysCode] 不能为空!");
        }
        if (!taskStepSet.getStepNo().isEmpty()) {
            queryWrapper.eq(BatchDailyBasicTaskStepSet::getStepNo, taskStepSet.getStepNo());
        }
        if (!taskStepSet.getStepName().isEmpty()) {
            queryWrapper.like(BatchDailyBasicTaskStepSet::getStepName, taskStepSet.getStepName());
        }
        Page<BatchDailyBasicTaskStepSet> batchDailyBasicTaskStepSetPage = new Page<>(taskStepSet.getPageNo(), taskStepSet.getPageSize());
        return Result.ok(dailyBasicTaskStepSetService.page(batchDailyBasicTaskStepSetPage, queryWrapper));
    }

    // todo-wuwei:待实现
    @ApiOperation(value = "跑批平台-获取日间跑批执行日志", notes = "获取日间跑批执行日志")
    @PostMapping("/getDailyTaskLogList")
    public Result<BatchDailyExecResp> getDailyTaskLogList(@RequestBody() BatchDailyExecReq req) {

        return Result.ok();
    }

    /**
     * 取消日间跑批计划
     *
     * @param taskPublish {"batchSysCode":"XXXXX","taskPubId":"XXXXXXXX" }
     * @return 操作结果
     */
    @ApiOperation(value = "跑批平台-取消日间跑批计划", notes = "取消日间跑批计划")
    @PostMapping("/cancelDailyTask")
    public Result<String> cancelDailyTask(@RequestBody() BatchDailyCancelReq taskPublish) {
        taskPublish.setBatchSysCode(XssFilterUtils.filterXss(taskPublish.getBatchSysCode()));
        taskPublish.setTaskPubId(XssFilterUtils.filterXss(taskPublish.getTaskPubId()));
        Result<String> checkResult = taskDailyExecFactory.checkCancelDailyTask(taskPublish);

        if (!checkResult.isSuccess()) {
            checkResult.setMessage("日间跑批计划取消验证失败！" + checkResult.getMessage());
            return checkResult;
        }

        Result<String> confirmDailyTaskResult = taskDailyExecFactory.cancelDailyTask(taskPublish);

        if (!confirmDailyTaskResult.isSuccess()) {
            confirmDailyTaskResult.setMessage("日间跑批计划取操作证失败！" + confirmDailyTaskResult.getMessage());
            return confirmDailyTaskResult;
        }

        return Result.ok("日间跑批计划取消成功!");

    }

    /**
     * 提交日间跑批计划
     *
     * @param taskPublish {    "batchSysCode":"MWBP",    "stepNo":"stepNo001",   "startDate":"20250625",    "endDate":"20250626",
     *                    execCycle":"daily@145902",    "stepParamsVersion":"1.0",    "stepParams":"{'test':'9999'}",    isReplay":"0"}
     * @return 操作结果
     */
    @ApiOperation(value = "跑批平台-提交日间跑批计划", notes = "提交日间跑批计划")
    @PostMapping("/confirmDailyTask")
    public Result<String> confirmDailyTask(@RequestBody() BatchDailyConfirmReq taskPublish) {

        taskPublish.setBatchSysCode(XssFilterUtils.filterXss(taskPublish.getBatchSysCode()));
        taskPublish.setStartDate(XssFilterUtils.filterXss(taskPublish.getStartDate()));
        taskPublish.setEndDate(XssFilterUtils.filterXss(taskPublish.getEndDate()));
        taskPublish.setStepParamsVersion(XssFilterUtils.filterXss(taskPublish.getStepParamsVersion()));
        taskPublish.setExecCycle(XssFilterUtils.filterXss(taskPublish.getExecCycle()));
        taskPublish.setStepNo(XssFilterUtils.filterXss(taskPublish.getStepNo()));
        taskPublish.setIsReplay(XssFilterUtils.filterXss(taskPublish.getIsReplay()));
        taskPublish.setTaskPubId(XssFilterUtils.filterXss(taskPublish.getTaskPubId()));


        Result<String> checkResult = taskDailyExecFactory.checkConfirmDailyTask(taskPublish);
        if (!checkResult.isSuccess()) {
            checkResult.setMessage("日间跑批计划提交验证失败！" + checkResult.getMessage());
            return checkResult;
        }
        Result<String> confirmDailyTaskResult = taskDailyExecFactory.confirmDailyTask(taskPublish);
        if (!confirmDailyTaskResult.isSuccess()) {
            confirmDailyTaskResult.setMessage("日间跑批计划提交操作失败！" + confirmDailyTaskResult.getMessage());
            return confirmDailyTaskResult;
        }

        return Result.ok("日间跑批计划提交成功!");


    }
//
//    @ApiOperation(value = "跑批平台-处理资金交易对账差错", notes = "处理资金交易对账差错")
//    @PostMapping("/optTradeCapitalCheckError")
//    public boolean optTradeCapitalCheckError(@RequestParam() String errorSerno, @RequestParam() String optDealStatus, @RequestParam(required =
//    false) String optDealSummary) {
//        // 差错状态 1 线上处理 2 线下处理
//        if (!(optDealStatus.equals(EnumUtil.资金交易对账差错表_差错状态_人工线上处理) || optDealStatus.equals(EnumUtil.资金交易对账差错表_差错状态_人工线下处理))) {
//            return false;
//        }
//        boolean result = taskExecFactory.optTradeCapitalCheckError(errorSerno, optDealStatus, optDealSummary);
//        // 如果是线上处理 在更新完 资金对账差错流水后 ，异步执行 调账操作
//        if (optDealStatus.equals(EnumUtil.资金交易对账差错表_差错状态_人工线上处理) && result) {
//            batchExecService.asyncDoTradeCapitalCheckError(errorSerno);
//        }
//        return result;
//    }


    // todo-wuwei:待确认
    @ApiOperation(value = "跑批平台-获取跑批日期", notes = "跑批平台-获取跑批日期")
    @PostMapping("/getExeDate")
    public String getExeDate() {
        String startTime = ConvertToUtil.getRunningTime();

        log.info("跑批平台-获取跑批日期开始");
        String mwbpTransDay = taskBuilder.getDayBy(-1);
        log.info("跑批平台-获取跑批日期结束 操作耗时：" + ConvertToUtil.getRunningTime(startTime));

        return mwbpTransDay;
    }

    // todo-wuwei:待确认
    //@ApiOperation(value = "跑批平台-提醒客户未提货短信发送手工处理", notes = "跑批平台-提醒客户未提货短信发送手工处理")
    //@PostMapping("/noteSendToUser")
    //public String noteSendToUser() {
    //    log.info("手动执行批量发送提货短信提醒开始");
    //    noteBatchTaskService.process();
    //    log.info("手动执行批量发送提货短信提醒结束");
    //    return "OK";
    //}
}
